//
//  PlayerViewController.m
//  MMLOOK
//
//  Created by BraveMatch on 15/10/8.
//  Copyright (c) 2015年 武俊娥. All rights reserved.
//

#import "PlayerViewController.h"
#import "STKAudioPlayer.h"
#import "PlayerView.h"
#import "MBProgressHUD.h"
#import "UIImageView+WebCache.h"
#import "MusicHandle.h"
#define OffWidth [UIScreen mainScreen].bounds.size.width / 375
#define OffHeight [UIScreen mainScreen].bounds.size.height / 667
@interface PlayerViewController ()<STKAudioPlayerDelegate>
{
    UILabel *huanchong;
    PlayerView *player;
    NSInteger count;
}
@property (nonatomic, retain) UIButton *preButton;
@property (nonatomic, retain) UIButton *playButton;
@property (nonatomic, retain) UIButton *nextButton;
@property (nonatomic, retain) UIImageView *backImageView;
@property (nonatomic, retain) UILabel *songNameLabel;
@property (nonatomic, copy) NSString *songName;
@property (nonatomic, retain) UILabel *singerNameLabel;
@property (nonatomic, copy) NSString *singName;

@property (nonatomic, retain) UIButton *voiceButton;
@property (nonatomic, retain) UILabel *currentPlaybackTime;
@property (nonatomic, retain) UILabel *totalPlaybackTime;


@property (nonatomic, copy) NSString *detail;
@property (nonatomic, assign) NSInteger songLength;
//@property (nonatomic, retain) UILabel *songDetail;
@property (nonatomic, retain) UIImageView *backImage;
@property (nonatomic, retain) MBProgressHUD *hud;
@property (nonatomic, retain) UISlider *slider;
@property (nonatomic, retain) UISlider *voiceSlider;
@property (nonatomic, retain) NSTimer *mytime;
@property (nonatomic, retain) UIButton *playStyle;


@end

@implementation PlayerViewController
- (void)dealloc
{
    [_preButton release];
    [_backImageView release];
    [_songNameLabel release];
    [_songName release];
    [_singerNameLabel release];
    [_singName release];
    [_detail release];
    [_backImage release];
    [_hud release];
    [_voiceButton release];
    [_currentPlaybackTime release];
    [_totalPlaybackTime release];
    [_slider release];
    [_voiceSlider release];
    [_mytime release];
    [_playStyle release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"STATE"] isEqualToString:@"YES"]) {
        _playButton.selected= YES;
    }
    else if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"STATE"] isEqualToString:@"NO"])
    {
        _playButton.selected= NO;
        
    }


}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];

    //初始化播放器
    
    player = [PlayerView shareHandleController];
    player.delegate = self;
    
    
    NSNotificationCenter *center=[NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(cene) name:@"MaxTime" object:nil];
    
    
    self.backImageView = [[UIImageView alloc] initWithFrame:self.view.frame];
    self.backImageView.image = [UIImage imageNamed:@"4.jpg"];
    [self.view addSubview:_backImageView];
    [_backImageView release];
    
    [self createSubView];
    
}



-(void)cene{
    
    [self nextAction];
}

-(void)createSubView
{
    self.backImage = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 320) / 2, 80, 320*OffWidth, 320*OffHeight)];
    self.backImage.clipsToBounds = YES;
    self.backImage.layer.cornerRadius = 160 ;
    [self.view addSubview:_backImage];
    
    NSString *str= [MusicHandle shareDan].imageUrl;
    [_backImage sd_setImageWithURL:[NSURL URLWithString:str]];
    
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 20, 40*OffWidth, 40*OffHeight);
    [backButton setImage:[UIImage imageNamed:@"fanhui.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    
    
    self.songNameLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40*OffHeight)];
    [_songNameLabel setCenter:CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/1.5)];
    [_songNameLabel setFont:[UIFont fontWithName:@"AmericanTypewriter-Bold" size:25.0]];
    //负值
    _songNameLabel.text=[MusicHandle shareDan].singname;
    _songNameLabel.textColor=[UIColor blackColor];
    _songNameLabel.textAlignment=1;
    [self.view addSubview:_songNameLabel];
    
    
    //歌手名字
    self.singerNameLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30*OffHeight)];
    [_singerNameLabel setCenter:CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/1.3)];
    [_singerNameLabel setFont:[UIFont fontWithName:@"G_singNamee" size:15.0]];
    _singerNameLabel.textColor=[UIColor blackColor];
    _singerNameLabel.text= [MusicHandle shareDan].singername;
    _singerNameLabel.textAlignment=1;
    [self.view addSubview:_singerNameLabel];
    

    
    
    self.voiceButton=[UIButton buttonWithType:UIButtonTypeCustom];
    _voiceButton.frame=CGRectMake(self.view.frame.size.width-60, self.view.frame.size.height-63, 40*OffWidth, 40*OffHeight);
    [_voiceButton setImage:[UIImage imageNamed:@"shengyin.png"] forState:UIControlStateNormal];
    [_voiceButton addTarget:self action:@selector(hidden:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_voiceButton];
    
    
    //开始时间
    self.currentPlaybackTime = [[UILabel alloc] initWithFrame:CGRectMake(5,self.view.frame.size.height-64-10 - 25 , 50*OffWidth, 25*OffHeight)];
    _currentPlaybackTime.font =[UIFont boldSystemFontOfSize:14.0f];
    _currentPlaybackTime.textAlignment = NSTextAlignmentCenter;
    _currentPlaybackTime.textColor = [UIColor blackColor];
    _currentPlaybackTime.text = @"00:00";
    [self.view addSubview:_currentPlaybackTime];
    
    
    //总长时间
    self.totalPlaybackTime = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width-53, self.view.frame.size.height-64-10 - 25 , 50*OffWidth, 25*OffHeight)];
    _totalPlaybackTime.font =[UIFont boldSystemFontOfSize:14.0f];
    _totalPlaybackTime.textAlignment = NSTextAlignmentCenter;
    _totalPlaybackTime.textColor = [UIColor blackColor];
    _totalPlaybackTime.text = @"00:00";
    [self.view addSubview:_totalPlaybackTime];
     self.mytime=[NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
    
    
    //进度条
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(0,self.view.frame.size.height-99, self.view.frame.size.width , 5*OffHeight)];
    _slider.continuous = YES;
    _slider.backgroundColor=[UIColor blueColor];
    _slider.minimumTrackTintColor = [UIColor cyanColor];
    _slider.maximumTrackTintColor = [UIColor whiteColor];
    [_slider addTarget:self action:@selector(PlaySlider:) forControlEvents:UIControlEventValueChanged];
    //progress.Value = player.progress;
    [_slider setThumbImage:[UIImage imageNamed:@"yuan.png"] forState:UIControlStateNormal];
    [self.view addSubview:_slider];
    huanchong=[[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-30, self.view.frame.size.height-64-10 - 20-20-12, self.view.frame.size.width/3, 40*OffHeight)];
    huanchong.textColor=[UIColor whiteColor];
    [self.view addSubview:huanchong];
    
    
    //声音控件
    self.voiceSlider= [[UISlider alloc] initWithFrame:CGRectMake(self.view.frame.size.width-110, self.view.frame.size.height-170, 130*OffWidth, 5*OffHeight)];
    _voiceSlider.maximumValue=20;
    _voiceSlider.minimumValue=0;
    _voiceSlider.minimumTrackTintColor = [UIColor cyanColor];
    _voiceSlider.maximumTrackTintColor = [UIColor lightGrayColor];
    [_voiceSlider setThumbImage:[UIImage imageNamed:@"yuan"] forState:UIControlStateNormal];
    _voiceSlider.value=4;
    _voiceSlider.hidden=YES;
    [_voiceSlider addTarget:self action:@selector(volumeSet:) forControlEvents:UIControlEventValueChanged];
    _voiceSlider.transform= CGAffineTransformMakeRotation(-90* M_PI/180);
    [self.view addSubview:_voiceSlider];
    

    
    
    
    
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playButton.frame = CGRectMake(self.view.frame.size.width/2-64/2, self.view.frame.size.height-64-10, 64*OffWidth, 64*OffHeight);
    [_playButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    [_playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateSelected];
    [_playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playButton];
    
    
    //上一首
    
    self.preButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.preButton.frame = CGRectMake(_playButton.frame.origin.x-60, _playButton.frame.origin.y+8, 48*OffWidth, 48*OffHeight);
    [self.preButton setImage:[UIImage imageNamed:@"shangyishou.png"] forState:UIControlStateNormal];
    [self.preButton addTarget:self action:@selector(preAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.preButton];
    [_preButton release];
    
    //下一首
    
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _nextButton.frame = CGRectMake(_playButton.frame.origin.x+70, _playButton.frame.origin.y+8, 48*OffWidth, 48*OffHeight);
    [_nextButton setImage:[UIImage imageNamed:@"xiayishou.png"] forState:UIControlStateNormal];
    [_nextButton addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextButton];
    
    
    
    //播放模式
    
    self.playStyle = [UIButton buttonWithType:UIButtonTypeCustom];
    _playStyle.frame =  CGRectMake(5, _preButton.frame.origin.y, 48*OffWidth, 48*OffHeight);
    [_playStyle setImage:[UIImage imageNamed:@"xunhuan.png"] forState:UIControlStateNormal];
    [_playStyle addTarget:self action:@selector(playStyleAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_playStyle];
    
    

}


-(void)backAction:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}


-(void)PlaySlider:(id)sender{
    if (player) {
        UISlider * processSlider = sender;
        [player seekToTime:processSlider.value];
        
    }
    
}
//音量隐藏
-(void)hidden:(UIButton *)voiceButton
{ if (voiceButton.selected == NO)
{
    voiceButton.selected = YES;
    [_voiceSlider setHidden:NO];
    
}
else
{
    [_voiceSlider setHidden:YES];
    voiceButton.selected = NO;
}
    
    
}



//音量设置
-(void)volumeSet:(UISlider*)slider
{
    [player setVolume:slider.value];
}


//显示时间
- (void)track
{
    if (self.slider) {
        self.slider.maximumValue = player.duration;
        self.slider.value = player.progress;
        NSInteger proMin = (NSInteger)player.progress / 60;
        NSInteger proSec = (NSInteger)player.progress % 60;
        NSInteger durMin = (NSInteger)player.duration / 60;
        NSInteger durSec = (NSInteger)player.duration % 60;
        
        _currentPlaybackTime.text = [NSString stringWithFormat:@"%02ld:%02ld", (long)proMin, (long)proSec];
        _totalPlaybackTime.text=[NSString stringWithFormat:@"%02ld:%02ld" , (long)durMin, (long)durSec];
        huanchong.text = player.state == STKAudioPlayerStateBuffering ? @"缓冲中..." : @"";
        huanchong.textColor = [UIColor blackColor];
        
       // NSLog(@"======显示时间");
    }
}



-(void)playAction:(UIButton *)playButton
{
    if (playButton.selected == NO)
    {
        playButton.selected = YES;
        [player pause];
        [[NSUserDefaults standardUserDefaults] setValue:@"YES" forKey:@"STATE"];
        CFTimeInterval pausedTime = [self.backImage.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        self.backImage.layer.speed = 0.0;
        self.backImage.layer.timeOffset = pausedTime;
        NSLog(@"======");
    }
    else
        
    {
        [player resume];
        [[NSUserDefaults standardUserDefaults] setValue:@"NO" forKey:@"STATE"];
        CFTimeInterval pausedTime = [self.backImage.layer timeOffset];
        self.backImage.layer.speed = 0.2;
        self.backImage.layer.timeOffset = 0.0;
        self.backImage.layer.beginTime = 0.0;
        CFTimeInterval timeSincePause = [self.backImage.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
        self.backImage.layer.beginTime = timeSincePause;
        playButton.selected = NO;
    }
    
    NSLog(@"========暂停");
    

}


//歌名和歌手名字方法
- (void)nameGet:(MyMusicModel *)model
{
     _songNameLabel.text = model.name;
    self.singerNameLabel.text= model.singerName;
    NSLog(@"singerNameLabel = %@",model.name);
    [MusicHandle shareDan].singname = model.name;

   [MusicHandle shareDan].singername = model.singerName;
    NSLog(@"singName = %@",model.name);
    
}



//选取歌曲音质(MP3)
- (void)playMusic:(NSInteger)playIndex
{
    MyMusicModel *model = [[MusicHandle shareDan].urlarray objectAtIndex:playIndex];
    [self nameGet:model];
    if (model.url) {
        [player play:model.url];
    }else
    {
        if(model.auditionList.count >2) {
            NSDictionary *dic = [model.auditionList objectAtIndex:1];
            NSString *url = [dic objectForKey:@"url"];
            [player play:url];
        }if (model.auditionList.count==1) {
            NSDictionary *dic = [model.auditionList objectAtIndex:0];
            NSString *url = [dic objectForKey:@"url"];
            [player play:url];
        }
    }
}

-(void)preAction:(id)sender
{
    NSLog(@"======上一曲");
    
    if ([[MusicHandle shareDan].urlarray count]!=0) {
        self.playerIndex-=1;
        if (self.playerIndex<0) {
            self.playerIndex = 0;
            _hud.labelText = @"第一首歌曲";
        }
        [self playMusic:self.playerIndex];
    }

    
}

-(void)nextAction
{
    NSLog(@"======下一曲");
    
    
    if ([MusicHandle shareDan].way == PlayWithWaySole) {//如果为顺序循环播放
        if (self.playerIndex == [[MusicHandle shareDan].urlarray count]-1) {
            NSLog(@"playerIndex = %ld",_playerIndex);
            self.playerIndex  = 0;
            [self playMusic:self.playerIndex ];
            return;
        }
        [self playMusic:++self.playerIndex ];
    }
    if (([MusicHandle shareDan].way  == PlayWithWayRandom)){// 如果是随机
        self.playerIndex  = arc4random() % [MusicHandle shareDan].urlarray.count;
        [self playMusic:self.playerIndex ];
    }
    if (([MusicHandle shareDan].way  == PlayWithWayOneSongCirculation))
    { // 如果是单曲
        [self playMusic:self.playerIndex ];
    }

}


-(void)playStyleAction:(id)sender
{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _hud.mode = MBProgressHUDModeText;
    [_hud show:YES];
    [_hud hide:YES afterDelay:1];
    [self.view addSubview:_hud];
    if ([MusicHandle shareDan].way == PlayWithWayOneSongCirculation) {//单曲循环播放
        [_playStyle setImage:[UIImage imageNamed: @"suiji.png"] forState:UIControlStateNormal];
        [MusicHandle shareDan].way = PlayWithWayRandom;
        _hud.labelText = @"随机";
        [MusicHandle shareDan].way = PlayWithWayRandom;
        return;
    }
    if ([MusicHandle shareDan].way == PlayWithWayRandom){//随机播放
        [_playStyle setImage:[UIImage imageNamed:@"xunhuan.png"] forState:UIControlStateNormal];
        [MusicHandle shareDan].way = PlayWithWaySole;
        _hud.labelText = @"顺序";
        return;
    }
    else{//顺序循环
        [_playStyle setImage:[UIImage imageNamed:@"danqu.png"] forState:UIControlStateNormal];
        [MusicHandle shareDan].way = PlayWithWayOneSongCirculation;
        _hud.labelText = @"单曲";
        return;
    }
    
}




// 协议方法
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"开始播放");
    
    
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"完成加载");
}


/// Raised when the state of the player has changed
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    
}
/// Raised when an item has finished playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    if (audioPlayer.state==STKAudioPlayerStateStopped) {
        
        
        NSNotificationCenter *playAnimation = [NSNotificationCenter defaultCenter];
        [playAnimation postNotificationName:@"MaxTime" object:nil];
        
    }
    
    
}
/// Raised when an unexpected and possibly unrecoverable error has occured (usually best to recreate the STKAudioPlauyer)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    NSLog(@"错误原因: %d", errorCode);
}


/// Optionally implemented to get logging information from the STKAudioPlayer (used internally for debugging)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer logInfo:(NSString*)line
{
    NSLog(@"信息: %@", line);
}
/// Raised when items queued items are cleared (usually because of a call to play, setDataSource or stop)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didCancelQueuedItems:(NSArray*)queuedItems
{
    NSLog(@"未知");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
